$(function() {
  var token = 'ACCESS_TOKEN';
  var loginCompanyClass = "LOGIN_COMPANYCLASS";
  var companyClass=$.cookie(loginCompanyClass);
  var accessToken = $.cookie(token);
  var encode = encodeURI("我的面料");//跳转到面料详情条件转码
  //展馆用户没有款号设置功能
  if (companyClass=="2"&&$(".form-item").find("a").text()=="款号设置"){
    $(".form-item").find("a").hide();
  }
  $(".my-material-titl").addClass("active");

  $('.nav-item').eq(1).addClass('active')
  var objectTpl = $('#objectTemplate').html();
  //面料类型
  Interface.invoke('FBC_FABRIC_CLASS_QUERY', {
    upClassCode: 'root'
  }, function(code, msg, info) {
    var classes = info['fabricClass'];
    if ($.isArray(classes)) {
      for(var i = 0, count = classes.length; i < count; ++i){
        $('#upViewFabricType').append('<option value='+classes[i].classCode+'>'+classes[i].className+'</option>');
        $('#downViewFabricType').append('<option value='+classes[i].classCode+'>'+classes[i].className+'</option>');
      }
    }
  });
  //织物类型
  Interface.invoke('FBC_FABRIC_WEAVE_QUERY', {
    upWeaveCode: 'root'
  },function(code, msg, info) {
    var weave = info['weave'];
    if($.isArray(weave)){
      for(var i = 0, count = weave.length; i < count; ++i){
        $('#upViewWeaveType').append('<option value='+weave[i].weaveCode+'>'+weave[i].weaveName+'</option>');
        $('#downViewWeaveType').append('<option value='+weave[i].weaveCode+'>'+weave[i].weaveName+'</option>');
      }
    }
  });
  //面料成分
  Interface.invoke('FBC_FABRIC_COMPSN_QUERY', {
      upCompsnKey: '1'
    },
    function(code, msg, info) {
      var composn = info['composn'];
      if($.isArray(composn)){
        for(var i = 0, count = composn.length; i < count; ++i){
          $('#upViewCompsn').append('<option value='+composn[i].compsnCode+'>'+composn[i].compsnName+'</option>');
          $('#downViewCompsn').append('<option value='+composn[i].compsnCode+'>'+composn[i].compsnName+'</option>');
        }
      }
    });
  /**
   * 设置分页数据
   */
  function setPagination(pagination, callback){
    pagination.pageCount = pagination.pageCount * 1;
    pagination.pageNo = pagination.pageNo * 1;
    pagination.pageSize = pagination.pageSize * 1;
    pagination.totalCount = pagination.totalCount * 1;
    pagination.totalPage = pagination.totalPage * 1;
    callback(pagination)
  }

  //获取认证信息
  var isAuthc="";
  function authentication(COMPANYKEY,obj,fabric){
    Interface.invoke('FBC_COMPANY_INFO_Q', {
      companyKey: COMPANYKEY
    }, function(code, msg, info) {
      // console.log(code, msg, info);
      if (code == 200) {
        //根据认证标签显示认证
        if (info.isAuthc=="0"){
          obj.find('#supplierName').html(fabric.supplierName);//未认证
          obj.find('#supplierName').prev("i").removeClass("icon_identify");
          obj.find('#supplierName').prev("i").addClass("icon_unidentify");
        }else{
          obj.find('#supplierName').html(fabric.supplierName);//已认证
          obj.find('#supplierName').prev("i").removeClass("icon_unidentify");
          obj.find('#supplierName').prev("i").addClass("icon_identify");
        }
      }
    }, true, true);
  }
  function setFabrics(fabrics, name) {
    if ($.isArray(fabrics)) {
      //隐藏冻结原因提示栏
      $(".hover-bg").hide();
      //显示全部数据
      for (var i =0, count = fabrics.length; i < count; i++) {
        var fabric = fabrics[i];
        var obj = $(objectTpl);
        //显示panel数据
        obj.appendTo($('#' + name + 'Container'));
        console.log("1")
        var id=obj.find('#detailsLink').find('img').attr('id','fabricImage' + i);
        repeatImg(id,fabric.fabricMainPict,200)
        obj.find('#fabricName').html(fabric.fabricName);
        obj.find('#fabricCode').html(fabric.fabricCode);
        fabricCode=fabric.fabricCode;
        authentication(fabric.supplierKey,obj,fabric);
        obj.find('.fabricStatus').attr('value',fabric.fabricStatus);
        obj.find('.auditStatus').attr('value',fabric.auditStatus);
        obj.find('.remark').attr('value',fabric.remark);
        $(".normal-object").hover(function(){
            $(this).addClass("active");
          },function(){
            $(this).removeClass("active");
          }
        );

        var composition = "";
        var com = fabric.composition.split(",");
        for (var int = 0; int < com.length; int++) {
          if (com[int] != "") {
            if (composition == "") {
              composition = replce(composition + com[int]);
            } else {
              com[int] = replce(com[int]);
              composition = composition + "," + com[int];
            }
          }
        }

        //数据格式化
        function format(num){
          var ge=(num*100)%10;
          var shi=((num*100)/10)%10;
          return ~~num+"."+~~shi+~~ge;

        }
        if(fabric.fabricPrice.substring(1) ==""){
          obj.find('#fabricPrice').html("面议");
        }else{
          obj.find('#fabricPrice').html(format(fabric.fabricPrice.substring(1)) + '<b>'+ fabric.priceUnitName + "/" + fabric.measureUnitName+'</b>');
        }

        var $editTo = obj.find(".editTo"),
          $downButton = obj.find(".downButton"),
          $deleteBtn = obj.find(".deleteBtn"),
          $corner = obj.find(".corner"),
          $hoverBg = obj.find(".hover-bg"),
          $downloadBtn = obj.find("button"),
          $download = obj.find(".download");
        function hideBtn(){
          $editTo.hide();
          $downButton.hide();
          $deleteBtn.hide();
          $corner.hide();
          $hoverBg.hide();
          $download.css({"height":"120px","padding-top":"47px"});

        }
        if(name=="normal"){
          if(companyClass==2){
            /*obj.find(".editTo").hide();
             obj.find(".downButton").hide();
             obj.find(".deleteBtn").hide();
             obj.find(".corner").hide();
             obj.find(".hover-bg").hide();
             obj.find(".download").css({"height":"120px","padding-top":"47px"});*/
            hideBtn();

          }else{
            $corner.hide();
            $hoverBg.hide();
            $downButton.show();
            $downloadBtn.css("padding","8px 35px");
            $downButton.css({"width":"70px","display":"inline-block"});//修复加上权限编码 出现样式错乱
            $editTo.css("width","70px");
            $deleteBtn.css("width","70px");
          }
        }
        if(name=="hidden"){
          if(companyClass==2){
            /* obj.find(".editTo").hide();
             obj.find(".downButton").hide();
             obj.find(".deleteBtn").hide();
             obj.find(".corner").hide();
             obj.find(".hover-bg").hide();
             obj.find(".download").css({"height":"120px","padding-top":"47px"})*/
            hideBtn();
          }else{
            //obj.find(".downButton").html("上架");
            $corner.hide();
            $hoverBg.hide();
            $downButton.hide();
            $editTo.css("width","50%");
            $deleteBtn.css("width","50%");
          }
        }
        if(name=="block"){
          if(companyClass==2){
            $editTo.hide();
            $downButton.hide();
            $deleteBtn.hide();
            $download.css({"height":"120px","padding-top":"47px"});
          }else{
            $downButton.hide();
            $editTo.css("width","50%");
            $deleteBtn.css("width","50%");
          }
          if(obj.find(".auditStatus").val().length !=0){
            $corner.hide();
          }
          $hoverBg.show();
          $hoverBg.find('span').text("冻结原因："+obj.find(".remark").val());
        }
        obj.find('.fabricKey').val(fabric.fabricKey);
        obj.find('#detailsLink').attr('href', 'details.html?key=' + fabric.fabricKey + "&from="+ encode+'&token='+accessToken+'');
        (function(fabric) {
          obj.find('.download>button').bind('click', function() {
            downloadDetailsimage(fabric.fabricKey,fabric.fabricCode);
            //window.location.href = fabric.fabricMainPict + '&isDown=true';
          });
          obj.find('#deleteButton').bind('click', function() {
            bootbox.confirm('确认删除面料 ' + fabric.fabricCode + ' 吗？', function(result) {
              if (result) {
                Interface.invoke('FBC_MYFABRIC_DEL', {
                  fabric: [{
                    fabricKey: fabric.fabricKey
                  }]
                }, function(code, msg, info) {
                  if (code == 200) {
                    bootbox.alert({
                      message:'面料删除成功',
                      callback:function(){
                        if(name=="normal"){
                          $('.pagination').remove();
                          setupTab('normal', 'D_FABRIC_NOMAL','D_FABRIC_PASS');
                        }
                        if(name=="hidden"){
                          $('.pagination').remove();
                          setupTab('hidden', 'D_FABRIC_HIDDEN','D_FABRIC_PASS');
                        }
                      }});

                  } else {
                    bootbox.alert('面料删除失败');
                  }
                });
              }
            });
          });
        })(fabric);

        if (i == count - 1) {
          obj.addClass('last');
        }

        $('.editTo').unbind('click').bind('click',function(){
          var fabricKey = $($(this).parents(".normal-object-edit").find(".fabricKey")).val();
          location.href = 'edit-ml-2?key='+fabricKey;
        })
        $('.downButton').unbind('click').bind('click',function(){
          var fabricStatus = $($(this).parents(".normal-object-edit").find(".fabricStatus")).val();
          var fabricKey = $($(this).parents(".normal-object-edit").find(".fabricKey")).val();
          if(fabricStatus == "上架"){//上架  D_FABRIC_NOMAL
            bootbox.confirm('确认下架面料吗？', function(result) {
              if(result){
                Interface.invoke('FBC_MAS_UPDFABRICSTATUS', {
                    fabricList:[{
                      fabricKey:fabricKey
                    }],
                    fabricStatus:'D_FABRIC_HIDDEN',
                    auditStatus:'D_FABRIC_PASS'
                  },
                  function(code, msg, info) {
                    if(code==200){
                      $('.pagination').remove();
                      setupTab('normal', 'D_FABRIC_NOMAL','D_FABRIC_PASS');
                    }
                  })
              }
            });
          }
          /*if(fabricStatus == "下架"){
           bootbox.confirm('确认上架面料吗？', function(result) {
           if(result){
           Interface.invoke('FBC_MAS_UPDFABRICSTATUS', {
           fabricList:[{
           fabricKey:fabricKey
           }],
           fabricStatus:'D_FABRIC_NOMAL',
           auditStatus:'D_FABRIC_PASS'
           },
           function(code, msg, info) {
           if(code==200){
           $('.pagination').remove();
           setupTab('hidden', 'D_FABRIC_HIDDEN','D_FABRIC_PASS');
           }
           })
           }
           });
           }*/
        })

      }

    }
  }
  var dataShow=function(name,code,audit,fabricClassCode,weaveCode,fabricCompsn,chartletFlag,keyWordCode,keyWordName){
    query()
    var p = Pagination.setup($('#' + name + 'Tab'), $('#' + name + 'Counter'), function(pageNo, callback, jumping) {
      $('#' + name + 'Container').html('');
      Interface.invoke('FBC_MYFABRIC_QUERY', {
        fabricStatus: code,
        auditStatus: audit,
        fabricClassCode:fabricClassCode,
        weaveCode:weaveCode,
        fabricCompsn:fabricCompsn,
        chartletFlag:chartletFlag,
        keyWord:keyWordCode,
        keyWord:keyWordName,
        pagination: {
          pageNo: pageNo + "",
          pageSize: 20 + ""
        }
      }, function(code, msg, info) {

        if(info.fabric && info.fabric.length==0){
          p.remove();
          $(".hideText").show();
        }else{
          p.show();
          $(".hideText").hide();
        }
        setFabrics(info.fabric, name);
        setPagination(info.pagination, callback);
      });
    }).hide();
  }

  var dataShow2=function(name,code,audit,fabricClassCode,weaveCode,fabricCompsn,chartletFlag,keyWordCode,keyWordName){
    query
    var p = Pagination.setup($('#' + name + 'Tab'), $('#' + name + 'Counter'), function(pageNo, callback, jumping) {
      $('#' + name + 'Container').html('');
      Interface.invoke('FBC_MYFABRIC_QUERY', {
        fabricStatus: code,
        auditStatus: audit,
        fabricClassCode:fabricClassCode,
        weaveCode:weaveCode,
        fabricCompsn:fabricCompsn,
        chartletFlag:chartletFlag,
        keyWord:keyWordCode,
        keyWord:keyWordName,
        pagination: {
          pageNo: pageNo + "",
          pageSize: 20 + ""
        }
      }, function(code, msg, info) {
        p.show();
        $(".hideText").hide();
        setPagination(info.pagination, callback);
      });
    }).hide();
  }

  function downloadDetailsimage(fabricKey,obj){  //根据面料的key查询图片
    Interface.invoke('FBC_MAS_GETFABRICINFO', {
      "fabricKey" : fabricKey
    }, function(code, msg, info) {
      if (code == 200) {
        Interface.invoke('FBC_MAS_GETMASFABRICPIC', {
          pictFileKey:info.pictFileKey
        }, function(code, msg, info) {
          var imageList = [];
          for (var int = 0; int < info.fabricViewLIst.length; int++) {
            imageList.push(info.fabricViewLIst[int].viewThumb);
          }
          var data =JSON.stringify(imageList)
          console.log(data)
          window.location.href="../action/downloadImage?url=" + encodeURIComponent(data)+"&fabricCode="+obj;
        }, false, false)
      }else{
        bootbox.alert("获取面料失败!");
      }
    }, false, false)
  }


  function setupTab(name,code,audit) {
    if(code=="D_FABRIC_NOMAL"){
      dataShow(name,code,audit);
      $("#upViewSearch").unbind('click').bind('click',function(){
        $('.pagination').remove();
        var upfabricClass = $("#upViewFabricType option:selected").attr("value");
        var upfabricWeave = $("#upViewWeaveType option:selected").attr("value");
        var upfabricCompsn = $("#upViewCompsn option:selected").attr("value");
        var upimageFlag = $("#upViewImageFlag option:selected").attr("value");
        var upfabricCode = $.trim($("#upViewInput").val());
        var upfabricName = $.trim($("#upViewInput").val());
        dataShow(name,code,audit,upfabricClass,upfabricWeave,upfabricCompsn,upimageFlag,upfabricCode,upfabricName);
      });
    }
    if(code=="D_FABRIC_HIDDEN"){
      dataShow(name, code,audit);
      $("#downViewSearch").unbind('click').bind('click',function(){
        $('.pagination').remove();
        var downfabricClass = $("#downViewFabricType option:selected").attr("value");
        var downfabricWeave = $("#downViewWeaveType option:selected").attr("value");
        var downfabricCompsn = $("#downViewCompsn option:selected").attr("value");
        var downimageFlag = $("#downViewImageFlag option:selected").attr("value");
        var downfabricCode = $.trim($("#downViewInput").val());
        var downfabricName = $.trim($("#downViewInput").val());
        dataShow(name,code,audit,downfabricClass,downfabricWeave,downfabricCompsn,downimageFlag,downfabricCode,downfabricName);
      });
    }
    if(code==""){
      dataShow(name, code,audit);
      $("#blockSearch").unbind('click').bind('click',function(){
        $('.pagination').remove();
        var blockfabricCode = $.trim($("#blockViewInput").val());
        var blockfabricName = $.trim($("#blockViewInput").val());
        dataShow(name,code,audit,'','','','',blockfabricCode,blockfabricName);
      });
    }
  }

  setupTab('normal', 'D_FABRIC_NOMAL','D_FABRIC_PASS');
  dataShow2('hidden', 'D_FABRIC_HIDDEN','D_FABRIC_PASS');
  dataShow2('block', '','D_FABRIC_BLOCK');
  /*setupTab('hidden', 'D_FABRIC_HIDDEN','D_FABRIC_PASS');
   setupTab('block', '','D_FABRIC_BLOCK');*/

  $('.tabBtn').click(function () {

    var idx = $('.tabBtn').index(this),
      $upload_ml =$("#upload_ml"),
      $hide_ml = $("#hide_ml"),
      $freedom_ml = $("#freedom_ml"),
      $tabPane = $('.tab-pane').eq(idx),
      $tabCont = $('.material-class-cont');
    $('.pagination').remove();
    switch (idx){
      case 0:
        $upload_ml.show();
        $hide_ml.hide();
        $freedom_ml.hide();
        setupTab('normal', 'D_FABRIC_NOMAL','D_FABRIC_PASS');
        break;
      case 1:
        $hide_ml.show();
        $upload_ml.hide();
        $freedom_ml.hide();
        setupTab('hidden', 'D_FABRIC_HIDDEN','D_FABRIC_PASS');
        break;
      case 2:
        $upload_ml.hide();
        $hide_ml.hide();
        $freedom_ml.show();
        setupTab('block', '','D_FABRIC_BLOCK');
        break;

    }
    $(this).addClass('active').siblings().removeClass('active');
    $tabPane.addClass('active')
      .siblings().removeClass('active');
    $tabCont.css('height',  $tabPane.height())
  });


  /*---------获取平台的数据 从中取出key 来查询扫面仪的按钮数据------------------*/
  function query(){

    var platfromKey = "";
    var paramsData = {
      "interfaceCode" : 'SYS_DICT_QUERY',
      "dictCode": "D_PRODUCT",
    }
    $.post(window.INTERFACE_URL+'/' + $.cookie('ACCESS_TOKEN'),paramsData,function(data){
      if(data.result.code == 200){
        var dictData = data.result.info.dict
        $.each(dictData,function(index,obj){
          if(obj.dictCode == "D_PRODUCT_FSM"){
            platfromKey = obj.dictKey
          }
        })
        /*----------根据上面的平台key来获取按钮的编码数据-------------------*/
        var param ={
          "interfaceCode" : "FBC_ROLE_MENUITEM_LIST",
          "usrKey" : $.cookie('LOGIN_USRKEY'),
          "roleKey" : "",
          "platformKey":platfromKey
        }
        jurisdicTionMenu(param,"buttonData");
      }
    })
  }
  /*--------------post请求的按钮或菜单的接口---------------------*/
  function jurisdicTionMenu(parameter,menuName){
    $.post(window.INTERFACE_URL+'/' + $.cookie('ACCESS_TOKEN'), parameter, function(data) {
      if(data.result.code==200){
        if(menuName == "buttonData"){
          setTimeout(function(){
            privlegeManager(data.result.info.menuItemList,"buttonListCode"); //按钮
          },1500)
        }
      }
    });
  }

  function privlegeManager(priList,code) {
    if(code == "buttonListCode"){
      setTimeout(function(){
        $.each(priList, function(i, pri) {
          console.log("4")
          $("." + pri.menuItemCode).removeClass('hide'); //按钮
        });
      },2000);
    }
  }

});
//截取成分的%
function replce(composition){
  if (composition.indexOf("%") == -1) {
    composition = composition.replace(/(\d+)([^\d]+)$/, "$1%$2");
  }
  return composition;
}